package proxyTest.serverProxy.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Author: jia
 * @Descirption:
 * @Date: 2018/5/16 14:05
 * @Modified By:
 */


public class ProxyServer {

    private int port;

    public ProxyServer(int port) {
        this.port = port;
    }

    //服务器只需一次性启动，不需要connect方法
    public void start() {
        try {
            ServerBootstrap b = new ServerBootstrap();
            EventLoopGroup boss = new NioEventLoopGroup();
            EventLoopGroup worker = new NioEventLoopGroup();
            final EventLoopGroup service = new NioEventLoopGroup();
            b.group(boss,worker);
            b.channel(NioServerSocketChannel.class);
            b.localAddress(port);
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new StringDecoder());
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(service,new ProxyServerHandler());
                }
            });
            //设置tcp参数
            b.option(ChannelOption.SO_BACKLOG,2048);
            b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            ChannelFuture future = b.bind().sync();
            System.out.println("ProxyServer===start");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
